//
//  MKUserAccount.swift
//  MKWeiBo2017
//
//  Created by nicolas on 2017/5/23.
//  Copyright © 2017年 nicolas. All rights reserved.
//


//对像归档和解档
//1、对象遵守NSCoding协议:知道对象要保存和解档哪些属性
//2、调用归档和解档的方法

import UIKit
//用户账号
class MKUserAccount: NSObject,NSCoding {
    ///用户授权的唯一票据
    var access_token: String?
    ///access_token的生命周期，单位是秒数
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
        
    }
    
    ///过期时间，方便比较时间
    var expiresDate: NSDate?
    
    ///授权用户的UID
    var uid: String?
    ///用户昵称
    var screen_name: String?
    ///用户头像地址
    var avatar_large: String?
    ///通过字典来创建模型
    init(dict: [String: AnyObject]) {
        super.init()
        
        setValuesForKeys(dict)
        
    }
    override func setValue(_ value: Any?, forKey key: String) {
        super.setValue(value, forKey: key)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    //打印对象
    override var description: String {
        
        get {
            return "用户账户: access_token:\(access_token), expires_in:\(expires_in), uid:\(uid)"
        }
    }
    
    //归档和解档
    ///解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as! String?
        expires_in = aDecoder.decodeDouble(forKey: "expires_in")
        uid = aDecoder.decodeObject(forKey: "uid") as! String?
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as! NSDate?
        screen_name = aDecoder.decodeObject(forKey: "screen_name") as! String?
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as! String?
        
    }
    
    ///归档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_in, forKey: "expires_in")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(screen_name, forKey: "screen_name")
        aCoder.encode(avatar_large,forKey:"avatar_large")
    }
    
    
    
}
